<?php

namespace app\admin\controller\wechatuser;

use app\admin\model\WechatDept;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Tree;
use think\Session;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{
    
    /**
     * WechatUser模型对象
     * @var \app\admin\model\WechatUser
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WechatUser;
        $this->view->assign("genderList", $this->model->getGenderList());
		$this->view->assign("isleaderList", $this->model->getIsleaderList());
        
		$this->view->assign("enableList", $this->model->getEnableList());

		//新加 start 添加人:gzy 添加时间2018年8月8日 09:10:00
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(false);
        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
		//print_r($groupList);die;
        $groupdata = [];

        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(1));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['id']] = $v['name'];
            }
					
        }
        else
        {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
		$position_data = [];
		foreach(TableList('Position') as $key => $val){
			$position_data[$val['id']] = $val['name'];
		}
		//职位信息
		$this->view->assign('position_data',$position_data);
		//新加 end
    }
    /**
     * 查看
     */
    public function index()
    {
		
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
			foreach ($list as $key => &$val){
				//部门信息
				$val['department_text'] = GetExplode(explode(',',$val['department']),'AuthGroup');
				//职位信息
				$val['position_text'] = GetExplode(explode(',',$val['position']),'Position'); 
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


  	/**
     * 成员添加
	 * @author gzy
	 * @date   2018年8月12日 15:25:00
     */
    public function add(){
        if ($this->request->isPost()) {
            $WechatParams = $params = $this->request->post("row/a");
            $dept = $this->request->post("department/a");
            $position = $this->request->post("position/a");
			//管理员数据
			$adminArr = [];
			$adminArr['username'] = $params['mobile'];
			$adminArr['nickname'] = $params['name'];
			$adminArr['password'] = $params['password'];
			$adminArr['avatar']   = $params['avatar_url'];
			$adminArr['email']    = $params['email'];
			$adminArr['status']    = $params['enable'] == 1?'normal':'hidden';
			$params['publish']    = \think\Session::get('admin')['userid'];
			$params['z_publish']    = \think\Session::get('admin')['userid'];
			$params['department'] = !empty($dept) ? implode(',',$dept):'';
			$params['position'] = !empty($position) ? implode(',',$position):'';
			$WechatParams['department'] = $dept;
			$WechatParams['position'] = GetExplode($position,'Position');
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
					//添加到微信
					$WechatInfo = GetUpdateApiData('User',$WechatParams,'add');
					$WechatInfo = !empty($WechatInfo)?json_decode($WechatInfo):$this->error(GetErrorLang('-3'));
					if ($WechatInfo->code !== 1) $this->error($WechatInfo->msg);
					unset($WechatParams);
					//赋值avatar_mediaid
					$params['avatar_mediaid'] = $WechatInfo->data->avatar_mediaid;
					$result = $this->model->validate('WechatUser.add')->save($params);
                    if ($result !== false) {
						//添加到管理员
						$params['uid'] = $uid = AdminUpdate($adminArr,$dept);
						$row = $this->model->get(['id' => $this->model->id]);
						//这里需要针对username和email做唯一验证
						$adminValidate = \think\Loader::validate('WechatUser');
						$adminValidate->rule([
							'userid' => 'require|max:50|unique:wechat_user,userid,' . $row->id,
							'email'    => 'require|email|unique:wechat_user,email,' . $row->id,
							'mobile'    => 'require|max:11|unique:wechat_user,mobile,' . $row->id,
						]);
						$result = $row ->validate('WechatUser.edit')->save($params);
						 if ($result !== false) {
							  $this->success();
						 } else {
							  $this->error($row->getError());
						 }
                       
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 成员编辑
	 * @author gzy
	 * @date   2018年8月12日 16:10:00
     */
    public function edit($ids = NULL){
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
					
            $WechatParams = $params = $this->request->post("row/a");
			$dept = $this->request->post("department/a");
			$position = $this->request->post("position/a");
			//管理员数据
			$adminArr = [];
			$adminArr['username'] = $params['mobile'];
			$adminArr['nickname'] = $params['name'];
			$adminArr['password'] = $params['password'];
			$adminArr['avatar']   = $params['avatar_url'];
			$adminArr['email']    = $params['email'];
			$adminArr['status']   = $params['enable'] == 1?'normal':'hidden';
			$params['z_publish']  = \think\Session::get('admin')['userid'];
			$params['department'] = !empty($dept) ? implode(',',$dept):'';
			$params['position'] = !empty($position) ? implode(',',$position):'';
			if (!$params['password']){
               unset($params['password']);
			} 
			$WechatParams['userid'] = $row->userid;
			$WechatParams['department'] = $dept;
			$WechatParams['position'] = GetExplode($position,'Position');
			//print_R($params);die;
            if ($params) {
                try {
					//编辑到微信
					$WechatInfo = GetUpdateApiData('User',$WechatParams,'edit');
					$WechatInfo = !empty($WechatInfo)?json_decode($WechatInfo):$this->error(GetErrorLang('-3'));
					//print_r($WechatInfo);die;
					if ($WechatInfo->code !== 1) $this->error($WechatInfo->msg);
					 //这里需要针对username和email做唯一验证
					$adminValidate = \think\Loader::validate('WechatUser');
					$adminValidate->rule([
						'userid' => 'max:50|unique:wechat_user,userid,' . $row->id,
						'email'    => 'require|email|unique:wechat_user,email,' . $row->id,
						'mobile'    => 'require|max:11|unique:wechat_user,mobile,' . $row->id,
					]);
					$result = $row ->validate('WechatUser.edit')->save($params);
                    if ($result !== false) {
						if(empty($row->uid)){
							//添加到管理员
							$upparams['uid'] = $uid = AdminUpdate($adminArr,$dept);
							$result = $row ->save($upparams);
						}else{
							//编辑到管理员
							$params['uid'] = $uid = AdminUpdate($adminArr,$dept,$row->uid);
						}
						$this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
			
        if ($ids) {
			
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
			//print_r(collection($list)->toArray());die;
            $count = 0;
			$info = [];
            foreach ($list as $k => $v) {
				//删除微信端
				$info['userid'] = $v->userid;
				$WechatInfo = GetUpdateApiData('User',$info,'delete');
				$WechatInfo = !empty($WechatInfo)?json_decode($WechatInfo):$this->error(GetErrorLang('-3'));
				if ($WechatInfo->code !== 1) $this->error($WechatInfo->msg);
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
		
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        $list = $this->model->onlyTrashed()->select();
        foreach ($list as $k => $v) {
            $count += $v->delete(true);
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 还原
     */
    public function restore($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        $list = $this->model->onlyTrashed()->select();
        foreach ($list as $index => $item) {
            $count += $item->restore();
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

   
   	/**
     * 成员更新 同步微信数据
	 * @author gzy
	 * @date   2018年8月14日 09:20:10
     */
    public function multi($ids = ""){
		$WechatInfo = GetUpdateApiData('User','','multi');
		$WechatInfo = !empty($WechatInfo) ? json_decode($WechatInfo) : $this->error(GetErrorLang('-3'));
		if ($WechatInfo->code !== 1) $this->error($WechatInfo->msg);
		$params = [];
		$upparams = [];
		foreach($WechatInfo->data->userlist as $key=>$val){
			//转换字段
			$val->department = !empty($val->department) ? implode(',',$val->department):'';
			$val->avatar_url = !empty($val->avatar) ? $val->avatar:'';
			if($val->department == 1) $val->department = '';
			$val->position = !empty($val->position) ? GetExplode(explode(',',$val->position),'Position','id','name') :'';
			//清除没用字段
			unset($val->avatar);
			unset($val->status);
			unset($val->extattr);
			unset($val->hide_mobile);
			unset($val->order);
			unset($val->qr_code);
			$val->z_publish = \think\Session::get('admin')['userid'];
			$oneInfo = $this->model->get(['userid' => $val->userid]);
			if(!empty($oneInfo)){
				$val->id = $oneInfo->id;
				$upparams[] = $val;
			}else{
				$val->publish = \think\Session::get('admin')['userid'];
				$params[] = $val;
			}
		}
		$result = 1;
		$resultup = 1;
		if(!empty($params)) $result = $this->model->saveAll(ObjectArray($params),false);
		if(!empty($upparams))$resultup = $this->model->saveAll(ObjectArray($upparams));
		if ($result && $resultup){
                $this->success();
        }
		$this->error();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

}
